#coding=utf8
from google.appengine.ext import db

import cPickle as pickle

def val_to_str(val):
    return pickle.dumps(val).encode('base64')

def str_to_val(s):
    return pickle.loads(s.decode('base64'))

'''golbal variable module'''

class GlobalVariable(db.Model):
    "implement global variables"
    global_name = db.StringProperty(required=True)
    # 一拍脑瓜想出来的方案
    # value -> dumps -> base64 -> string
    global_val = db.TextProperty(required=True)
    global_description = db.StringProperty(required=True)
    
def get_global_val(name):
    "get global variable value"
    gv = db.GqlQuery("SELECT * FROM GlobalVariable WHERE global_name = :1", name).get()
    if gv:
        return str_to_val(gv.global_val)
    return None

def set_global_val(name, val, description = 'nothing'):
    "set global variable value"
    if not name:
        return False
    gv = db.GqlQuery("SELECT * FROM GlobalVariable WHERE global_name = :1", name).get()
    if gv:
        gv.global_val = val_to_str(val)
        if gv.put():
            return True
    else:
        gv = GlobalVariable(global_name=name,
                            global_val=val_to_str(val),
                            global_description=description)
        if gv.put():
            return True
    return False

def delete_global_val(name):
    gv = db.GqlQuery("SELECT * FROM GlobalVariable WHERE global_name = :1", name).get()
    if gv:
        gv.delete()
        return True
    return False

# just for test
def clean_all_global_val():
    gvlst = db.GqlQuery("SELECT * FROM GlobalVariable").fetch(1000)
    if gvlst:
        for gv in gvlst:
            gv.delete()
